<?php

/**
 * board view page
 * @param $account
 */
function user_board_page($account, $action = NULL) {
  switch($action) {
    case 'get':
      global $user;

      $query = db_select('user_term', 'ut')
        ->fields('ut', array('tid'))
        ->condition('ut.uid', $account->uid)
        ->orderBy('ut.tid', 'DESC');

      $tids = $query->execute()->fetchCol();
      $terms = taxonomy_term_load_multiple($tids);

      // filter out private $terms for public view
      if($account->uid !== $user->uid) {
        foreach($terms as $tid => $term) {
          if(CommonHelper::is_private_board($term)) {
            unset($terms[$tid]);
          }
        }
      }

      $boards = array();
      foreach($terms as $term) {
        // get cover
        $field_cover = field_get_items('taxonomy_term', $term, 'field_cover');
        if($field_cover) {
          $term->cover = image_style_url('cover_640x400', $field_cover[0]['uri']);
        }
        else {
          $info = field_info_field('field_cover');
          if (!empty($info) && $info['settings']['default_image'] > 0) {
            $default_img_fid  = $info['settings']['default_image'];
            $default_img_file = file_load($default_img_fid);
            $term->cover = image_style_url('cover_640x400', $default_img_file->uri);
          }
        }
        $term->url = url("taxonomy/term/$term->tid");
        $links_count = TaxonomyHelper::term_nodes_count($term->tid);
        $term->links_count = format_plural($links_count, '1 link', '@count links');
        $term->private = CommonHelper::is_private_board($term);
        $boards[] = $term;
      }
      drupal_json_output($boards);
      break;

    case 'post':
      CommonHelper::check_token('user_board');

      $messages = array();
      $errors = array();
      $data = $_POST;

      if(empty($data)) {
        drupal_access_denied();
        drupal_exit();
      }

      if(!isset($data['name']) || empty($data['name'])) {
        $errors[] = t("Please give board a name");
      }

      $file = file_save_upload('file', array(
        // Validates file is really an image.
        'file_validate_is_image' => array(),
        // Validate extensions.
        'file_validate_extensions' => array('png gif jpg jpeg'),
      ));

      // If the file passed validation:
      if ($file) {
        $destination = 'public://covers';
        file_prepare_directory($destination);
        // Move the file into the Drupal file system.
        if ($file = file_move($file, $destination)) {
        }
        else {
          $errors[] = t("Failed to write the uploaded file to the site's file folder.");
        }
      }

      $voc = taxonomy_vocabulary_machine_name_load('board');

      // prepare term object
      $term = (object) array(
        'tid' => $data['tid'],
        'name' => $data['name'],
        'description' => '',
        'format' => 'plain_text',
        'vid' => $voc->vid,
        'field_cover' => array(
          'und' => array((array)$file)
        ),
        'field_privacy' => array(
          'und' => array(
            array('value' => $data['privacy'])
          )
        ),
        'field_category' => array(
          'und' => array(
            array('value' => $data['category'])
          )
        ),
      );

      if(empty($errors)) {
        // finally save term
        if(taxonomy_term_save($term)) {
          $messages[] = t("Board !board has been created",
            array('!board' => l($term->name, "taxonomy/term/$term->tid", array(
              'attributes' => array('class' => array('alert-link'))
            ))));
        }
      }

      $response = array(
        'errors' => $errors,
        'messages' => $messages
      );

      drupal_json_output($response);
      break;

    default:
      drupal_add_css(drupal_get_path('module', 'user_board') . '/css/user_board.css');

      $user_board_token = drupal_get_token('user_board');
      drupal_add_js(array(
        'user_board' => array(
          'uid' => $account->uid,
          'user_board_token' => $user_board_token,
          'board' => (object) array(
              'tid' => '',
              'name' => '',
              'field_category' => (object) array(
                  'und' => array(
                    (object) array(
                      'value' => 'other'
                    )
                  )
                ),
              'field_privacy' => (object) array(
                  'und' => array(
                    (object) array(
                      'value' => 'public'
                    )
                  )
                ),
              'user_board_token' => $user_board_token,
            )
        )
      ), 'setting');

      LibraryHelper::load(array(
        array('name' => 'angular'),
        array('name' => 'angular-sanitize'),
        array('name' => 'angular-file-upload'),
      ));

      drupal_add_js(drupal_get_path('module', 'helper') . '/js/crabii-validation-directive.js');
      drupal_add_js(drupal_get_path('module', 'user_board') . '/js/user_board.js');

      $addition = '';
      if($GLOBALS['user']->uid == $account->uid) {
        $addition = theme('user_board_add_panel') . theme('user_board_form');
      }

      $build = array(
        '#markup' => '
        <div ng-app="userBoardApp" ng-controller="userBoardController" uploader="uploader" class="grid-boards-wrapper clearfix">
          ' . theme('user_board_boards') . '
          ' . $addition . '
        </div>',
      );

      $build['#user_board'] = array(
        'title_prefix' => array(
          '#markup' => '<div class="user-board-header">' . theme('user_picture', array('account' => $account)),
        ),
        'title_suffix' => array(
          '#markup' => '<div class="absolute-current-path">' . CommonHelper::absolute_current_path() . '</div></div>',
        )
      );
      return $build;
      break;
  }
}
